﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;

public class TileMapManager : MonoBehaviour
{
    public Grid mainGrid;               //总栅格
    private Tilemap[] tilemaps;         //瓦片地图数组
    private Vector3Int testPostion;     //测试用坐标
    
    private Tile BoxTile;        //箱子的瓦片
    private Tile BarrelTile;     //桶的瓦片
    private Tilemap BoxMap;      //箱子的瓦片层
    private Tilemap BarrelMap;   //桶的瓦片层

    //在指定位置添加箱子
    private bool addBox(Vector3Int position)
    {
        return addTile(BoxMap,BoxTile,position);
    }
    //从指定位置移除箱子
    private bool removeBox(Vector3Int position)
    {
        return removeTile(BoxMap, position);

    }

    //在指定位置添加桶
    private bool addBarrel(Vector3Int position)
    {
        return addTile(BarrelMap, BarrelTile, position);
    }
    //从指定位置移除桶
    private bool removeBarrel(Vector3Int position)
    {
        return removeTile(BarrelMap, position);
    }


    //添加瓦片target到瓦片地图tilemap的指定位置position上 成功则返回true
    protected bool addTile(Tilemap tilemap,Tile target,Vector3Int position)
    {
        if(tilemap == null || target == null) return false;
        tilemap.SetTile(position, target);
        tilemap.RefreshAllTiles();
        return true;
    }
    //在瓦片地图tilemap上的指定位置position添加一个null的tile 做到清除瓦片的效果
    protected bool removeTile(Tilemap tilemap, Vector3Int position)
    {
        if (tilemap == null) return false;
        tilemap.SetTile(position, null);
        tilemap.RefreshAllTiles();
        return true;
    }
    //目前不知道是否有用的函数 理论上讲当前分层方式下瓦片地图的tag已经代表了一类Tile
    protected bool getTile(Tilemap tilemap, Vector3Int position, out TileBase target)
    {
        target = tilemap.GetTile(position);
        if (target != null)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    //自由坐标到瓦片地图坐标的转化函数
    public Vector3Int getIntPosition(Vector3 position)
    {
        int newX = 0 , newY = 0 , newZ = 0;
        //获取原位置对应的去除小数部分的数值 再生成一个0.5的分界线用以四舍五入
        int preX = (int)position.x; float nextX = preX + 0.5f;
        int preY = (int)position.y; float nextY = preY + 0.5f;
        int preZ = (int)position.z; float nextZ = preZ + 0.5f;
        //若原来的数的小数部分小于5 则会舍去 否则进位 来达到从自由的平面地图转化到瓦片地图坐标的功能
        newX = (position.x < nextX) ? preX : preX + 1;
        newY = (position.y < nextY) ? preY : preY + 1;
        newZ = (position.z < nextZ) ? preZ : preZ + 1;
        //根据获取的新整数坐标生成新的Vector3Int
        return new Vector3Int(newX,newY,newZ);
    }


    // Start is called before the first frame update
    void Start()
    {
        testPostion = new Vector3Int(0, 0, 0);
        tilemaps = mainGrid.GetComponentsInChildren<Tilemap>();    //从总栅格中获取瓦片地图
        //压缩TileMap数组 去除外围空区域
        for(int i = 0; i < tilemaps.Length; i++)
        {
            tilemaps[i].CompressBounds();
        }
    }
    // Update is called once per frame
    void Update()
    {

    }
}